package hydrap2p.gui.commands;

import hydrap2p.gui.FileTransferPanel;
import hydrap2p.gui.FilterLabelPanel;

import java.util.ArrayList;

import javax.swing.JOptionPane;

public class Cmd_FilterLabelPanel_DeleteLabel implements Command {

	@Override
	public void execute() {

		ArrayList<String> labels = FilterLabelPanel.getInstance().getLabels();
		int[] indices = FilterLabelPanel.getInstance().getLabelList()
				.getSelectedIndices();

		// they're trying to remove the "unlabelled" one
		if (indices.length == 1 && indices[0] == 1) {
			JOptionPane.showMessageDialog(null, "Cannot delete this entry.",
					"Invalid", JOptionPane.WARNING_MESSAGE);
			return;
		} else if (indices.length == 0) { // There are no entries selected
			JOptionPane.showMessageDialog(null, "No entries selected.",
					"Invalid", JOptionPane.WARNING_MESSAGE);
			return;
		} else if (labels.size() == 0) {
			JOptionPane.showMessageDialog(null, "Cannot delete these entries.",
					"Invalid", JOptionPane.WARNING_MESSAGE);
			return;
		}

		Object[] options = { "Yes", "Cancel" };
		int choice = JOptionPane.showOptionDialog(null,
				"Really delete the selected labels?", "Warning",
				JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null,
				options, options[0]);

		if (choice == 0) {
			for (int i : indices) {
				if (i >= 2 && i - 2 < labels.size()) // don't delete the first
														// two, ever; also, the
														// indices array seems
														// to have extra entries
														// when everything is
														// selected
				{
					// tell the file transfer panel to remove this label from
					// any listings that have it
					FileTransferPanel.getInstance().labelDeleted(
							labels.get(i - 2));
					labels.set(i - 2, null);
				}
			}

			// we need to separate this from the last for loop so that we don't
			// screw with the indices when removing
			for (int i = 0; i < labels.size(); i++) {
				if (labels.get(i) == null) {
					labels.remove(i);
					i--;
				}
			}

			FilterLabelPanel.getInstance().updateLabelList();
		}
		// else do nothing
	}

	@Override
	public String getCommand() {
		return this.getClass().getSimpleName();
	}

	@Override
	public void unexecute() {
		// TODO Auto-generated method stub

	}

}
